package com.java.mvc.framework.servlet;

import com.java.mvc.framework.annotation.MyAutowried;
import com.java.mvc.framework.annotation.MyController;
import com.java.mvc.framework.annotation.MyRequestMapping;
import com.java.mvc.framework.annotation.MyService;
import lombok.extern.log4j.Log4j2;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

@Log4j2
public class MyDispatcherServlet extends HttpServlet {
    Properties p = new Properties();

    private List<String> classNames = new ArrayList<>();


    private Map<String, Object> ioc = new HashMap<>();

    private Map<String, Method> handlerMapping = new HashMap<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        String application = config.getInitParameter("contextConfigLocation");
        System.out.println(application);
        //实现像spring ico容器初始化 di mvc
        //1.加载配置文件
        doloadConfig(application);

        //2.扫描配置文件中描述的相关的所有类
        doScanner(p.getProperty("scanPackage"));

        //3.实例化所有被扫描到的类，并存放到IOC容器中（自己实现IOC容器）
        doInstance();

        //4.依赖注入，DI从IOC容器中找到加上@autowried这个注解的属性，并找到其在IOC容器中的实例
        //动态赋值
        doAutowired();
        //5.构造URL和@controller中加了@requestmapping这个注解的方法和URL构造成一个对应关系
        //可以理解为map结构 key url value  method
        //这个操作是springmvc 中的最重要一点
        initHandlerMapping();
        log.info("My MVC IS INIT");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doDispatcher(req,resp);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //6等待用户请求，根据url 找到map中对应的method
        //通过反射调用方法
        this.doDispatcher(req,resp);
    }


    private void doloadConfig(String location) {
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(location);

        try {
            p.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    /**
     * 递归扫描,扫描出指定包下的完整类名
     */
    private void doScanner(String packageName) {

        URL url = this.getClass().getClassLoader().getResource("/" + packageName.replaceAll("\\.", "/"));
        File dir = new File(url.getFile());
        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                doScanner(packageName + "." + file.getName());
            } else {
                classNames.add(packageName + "." + file.getName().replace(".class", "").trim());
            }
        }
    }

    private void doInstance() {
        if (classNames.isEmpty()) {
            return;
        }
        try {
            for (String className : classNames) {
                Class<?> clazz = Class.forName(className);
                if (clazz.isAnnotationPresent(MyController.class)) {
                    String beanName = lowerFirst(clazz.getSimpleName());
                    ioc.put(beanName, clazz.newInstance());

                } else if (clazz.isAnnotationPresent(MyService.class)) {
                    //第一种形式，默认首字母小写
                    //第二种形式，如果自己起了名字，那就优先用自己定义的名字去匹配
                    //第三种形式，利用接口本身全称作为key,把其对应实现类的实例作为值
                    MyService service = clazz.getAnnotation(MyService.class);
                    String beanName = service.value();
                    if (!"".equals(beanName.trim())) {
                        ioc.put(beanName, clazz.newInstance());
                        continue;
                    }
                    Object instance = clazz.newInstance();
                    beanName = lowerFirst(clazz.getSimpleName());
                    ioc.put(beanName, clazz.newInstance());

                    Class<?>[] interfaces = clazz.getInterfaces();
                    for (Class<?> i : interfaces) {
                        ioc.put(i.getName(), instance);
                    }

                } else {
                    continue;
                }
            }
        } catch (Exception e) {

        }

    }

    private void doAutowired() {
        if (ioc.isEmpty()) {
            return;
        }
        ioc.forEach((key, value) -> {
            Field[] fields = value.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (!field.isAnnotationPresent(MyAutowried.class)) {
                    continue;
                }
                MyAutowried autowried = field.getAnnotation(MyAutowried.class);
                //技术是private 也要注入
                String beanName = autowried.value().trim();
                if ("".equals(beanName)) {
                    beanName = field.getType().getName();
                }
                field.setAccessible(true);
                //开始赋值
                try {
                    field.set(value, ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initHandlerMapping() {
        if (ioc.isEmpty()) {
            return;
        }
        ioc.forEach((key, value) -> {
            Class<?> clazz = value.getClass();
            if (!clazz.isAnnotationPresent(MyController.class)) {
                return;
            }
            String url = "";
            if (clazz.isAnnotationPresent(MyRequestMapping.class)) {
                MyRequestMapping requestMapping = clazz.getAnnotation(MyRequestMapping.class);
                url = requestMapping.value();
            }
            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                if (!method.isAnnotationPresent(MyRequestMapping.class)) {
                    continue;
                }
                MyRequestMapping requestMapping = method.getAnnotation(MyRequestMapping.class);
                String mapping = ("/" + url + "/" + requestMapping.value()).replaceAll("/+", "/");
                System.out.println(mapping + " : " + method);
                handlerMapping.put(mapping, method);
            }
        });
    }

    private void doDispatcher(HttpServletRequest request, HttpServletResponse response) {
        if (handlerMapping.isEmpty()) {
            return;
        }
        System.out.println(handlerMapping);
        String uri = request.getRequestURI();
        String contextPath = request.getContextPath();
        uri.replace(contextPath, "").replaceAll("/+", "/");
        Method method = handlerMapping.get(uri);
        if (null != method){
            //todo 获取类名和参数
          //  method.invoke()
        }
    }

    private String lowerFirst(String str) {
        char[] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }
}
